<?php
	// MySQL Database Info
	$dbhost = "";
	$dbuser = "";
	$dbpass = "";
	$dbname = "CONTRIB_droptables";

	// Connect to the MySQL database
	$db = mysql_connect($dbhost, $dbuser, $dbpass);
	if (!$db) {
		die('Could not connect: ' . mysql_error());
	}
	mysql_select_db($dbname, $db);

	/* Functions */
	function getUserID($username) {
		$query = "SELECT `id` FROM `user` WHERE `username` = '" . $username . "'";
		$result = mysql_query($query);
		if($row = mysql_fetch_array($result)) {
			return $row['id'];
		} else {
			$query = "INSERT INTO `user` (`username`) VALUES ('" . $username . "')";
			mysql_query($query);
			return getUserID($username);
		}
	}
	
	function getClasses($id) {
		if (is_numeric($id)) {
			$query = "SELECT `id`, `name` FROM `class` WHERE `userID` = " . $id;
			return mysql_query($query);
		}
		return null;
	}
	
	function validateUser($classID, $userID) {
		if (is_numeric($classID) && is_numeric($userID)) {
			$query = "SELECT `name` FROM `class` WHERE `userID` = " . $userID . " and `id` = " . $classID;
			$result = mysql_query($query);
			if($row = mysql_fetch_array($result)) {
				return TRUE;
			}
		}
		return FALSE;
	}
	
	function getRoster($id) {
		if (is_numeric($id)) {
			$query = "SELECT `name`, `imageURL` FROM `roster` WHERE `classID` = " . $id;
			return mysql_query($query);
		}
		return null;
	}
	
	function insertClass($userID, $class) {
		$query = "SELECT `id` FROM `class` WHERE `userID` = " . $userID . " AND `name` = '" . $class . "'";
		$result = mysql_query($query);
		if($row = mysql_fetch_array($result)) {
			return $row['id'];
		} else {
			$query = "INSERT INTO `class` (`userID`, `name`) VALUES (" . $userID . ", '" . $class . "')";
			mysql_query($query);
			return insertClass($userID, $class);
		}
	}
	
	function insertStudent($classID, $student, $imageURL) {
		$query = "SELECT `name` FROM `roster` WHERE `classID` = " . $classID . " AND `name` = '" . $student . "'" . " AND `imageURL` = '" . $imageURL . "'";
		$result = mysql_query($query);
		if($row = mysql_fetch_array($result)) {
			return $row['name'];
		} else {
			$query = "INSERT INTO `roster` (`classID`, `name`, `imageURL`) VALUES (" . $classID . ", '" . $student . "', '" . $imageURL . "')";
			mysql_query($query);
			return insertStudent($classID, $student, $imageURL);
		}
	}
	
	function import($username, $class, $student, $imageURL) {
		$userID = getUserID($username);
		$classID = insertClass($userID, $class);
		insertStudent($classID, $student, $imageURL);
		return TRUE;
	}
?>
